<?php

namespace App\Repository\Db;

use App\Repository\Contracts\FavoriteInterface;
use App\Repository\Contracts\UserInterface;
use Illuminate\Support\Facades\DB;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/7/17 3:04
 */
class FavoriteRepository extends Repository implements FavoriteInterface
{
    protected $rules = [
        'created' => [
            'uid' => 'required|integer',
            'target' => 'required',
            'target_id' => 'required|integer'
        ]
    ];

    protected $messages = [
        'uid.required'         => "用户 ID 不能为空",
        'uid.integer'          => "用户 ID 必须是整数",
        'target.required'      => "目标不能为空",
        'target_id.required'   => "目标  ID 不能为空",
        'target_id.integer'    => "目标  ID 必须是整数"
    ];

    protected function modelName()
    {
        return 'App\Model\Favorite';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        if ($favorite = $this->model->where('uid', $data['uid'])->where('target', $data['target'])
            ->where('target_id', $data['target_id'])->first()) {
            return $this->updateStatus([['field' => 'id', 'value' => $favorite->id, 'operation' => '=']], 1);
        }

        return $this->save($data);
    }

    public function updateStatus($map = [], $status = 1)
    {
        return $this->searchMap($map)->update(['status' => $status]);
    }

    public function lists($limit, $page, $map = [], $target)
    {
        $query = $this->searchMap($map);
        if ($target == '1') {
            $archiveYear = date("Y", strtotime("-2 year"));
            foreach ($map as $item) {
                if ($item['field'] = 'uid') {
                    $uid = $item['value'];
                }
            }
            $user = $this->container->make(UserInterface::class)->detail($uid);
            $query = $query->with('school')
                ->leftJoin('school_score', 'school_score.school_id', '=', 'favorite.target_id')
                ->where([
                    'school_score.year' => $archiveYear,
                    'school_score.batch' => 1,
                    'school_score.subject' => ($user['subject'] == 1 ? '文科' : '理科'),
                    'school_score.province_id' => $user['province_id']
                ]);
            $data = $query->orderBy('favorite.id', 'desc')->simplePaginate($limit, ['favorite.*','school_score.min_score',DB::raw('w_school_score.province_name as archive_province')], 'page', $page);
                  // //   调试
    //   $sql = str_replace("?", "'%s'", $query->toSql());
    //   $log = vsprintf($sql, $query->getBindings());
    //   var_dump($log);
    //   exit;
        } else {
            if ($target == '2') {
                $query = $query->with('major');
                } else {
                    $query = $query->with('plan');
                }
            $data = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);
        }
        $total = $query->count();
        $list = [];
        foreach ($data as $key => $val) {
            if ($target == '1') {
                $list[] = [
                    'id' => $val->school->id,
                    'name' => $val->school->name,
                    'logo' => $val->school->logo,
                    'is_985' => $val->school->is_985,
                    'is_211' => $val->school->is_211,
                    'type' => $val->school->type,
                    'property' => $val->school->property,
                    'subject_type' => $val->school->subject_type,
                    'education' => $val->school->education,
                    'archive_year' => $archiveYear,
                    'archive_province' => $val->archive_province,
                    'archive_score' => $val->min_score,
                    'archive_probability' => ($user['score'] > $val->min_score ? '70%' : '40%'),
                    'province_name' => $val->school->province_name,
                    'address' => $val->school->address,
                    'male_ratio' => $val->school->male_ratio,
                    'female_ratio' => $val->school->female_ratio,
                    'comprehensive_rank' => $val->school->comprehensive_rank,
                ];
            } elseif ($target == '2') {
                $list[] = [
                    'id' => $val->major->id,
                    'name' => $val->major->name,
                    'degree_type' => $val->major->degree_type,
                    'major_type' => $val->major->major_type,
                    'major_category' => $val->major->major_category,
                ];
            } else {
                $list[] = [
                    'id' => $val->plan->id,
                    'school_id' => $val->plan->school_id,
                    'school_name' => $val->plan->school->name,
                    'school_code' => $val->plan->school->code,
                    'year' => $val->plan->year,
                    'recruit_count' => $val->plan->recruit_count,
                ];
            }
        }

        return $this->simplePaginate('list', $list, $total);
    }
}